-- 第三方认证登陆
local httparg               = require("shared.api.httparg")
local response              = require("shared.api.response")
local config                = require("config")
local httpclient            = require "shared.http.client"
local util                  = require "proxy.game.common.util"
local tag                   = httparg.tag()
local assertion             = httparg.assertion

local ngx                   = _G.ngx
local get_response_spec     = util.get_response_spec
local fill_response_header  = util.fill_response_header
local is_match_content_type = util.is_match_content_type
local get_content_decoder   = util.get_content_decoder
local get_method            = util.get_method
local cjson                 = require "cjson.safe"
      cjson.encode_max_depth(32)
      cjson.decode_max_depth(32)



local oauth_provider    = ngx.var.oauth_provider
local accountGateWayUrl = config.ENV.ACCOUNTGATE_SERVICE
local ARGS = {
  tag.body('json', 'required'),

  code          = tag.json.code          ('string', 'required', assertion.non_empty_string()),
  code_type     = tag.json.code_type     ('string', assertion.non_empty_string()),
  redirect_uri  = tag.json.redirect_uri  ('string'),
  adjust        = tag.json.adjust    ('map')
}





local ip = ngx.req.get_headers()['IP']
ngx.log(ngx.ERR,ip)
local call_nsq=function(loginRes)
    --nsq
    loginRes.ip = ip
    loginRes.provider = oauth_provider
    local producer = require "resty.nsq.producer"
    local NSQ= config._Event_Bus_Nsq

    local prod = producer:new()
    local ok, err = prod:connect(NSQ.host,NSQ.port)
    -- local ok, err = prod:connect("10.101.137.80",4150)
    if not ok then
        ngx.say("failed to connect: ", err)
        return
    end
    local nsqMsg= loginRes
    local NSQ_MSG_BODY= cjson.encode(nsqMsg)
    ngx.log(ngx.ERR, NSQ_MSG_BODY)
    local  ok, err = prod:pub(NSQ.active,NSQ_MSG_BODY )
    if not ok then
        ngx.say("failed to pub: ", err)
        return
    end
    ok, err = prod:close()
    if not ok then
        ngx.say("failed to close: ", err)
        return
    end

end


--获取绑定账户信息
local getAccountIdInfo=function()
  local res={}
  local ADDRESS = accountGateWayUrl
  --后面接的path
  local ACTION  = string.format("%s/account",ngx.var.oauth_provider)

  if not ADDRESS or not ACTION then
    ngx.status = ngx.HTTP_NOT_FOUND
    ngx.exit(ngx.OK)
  end

  --从rgs取实际的url
  do
    local location = ngx.unescape_uri(ADDRESS..ACTION)
    local method   = "PEEK"
    local headers  = ngx.req.get_headers()
    ngx.req.read_body()
    --local data   = ngx.req.get_body_data()
    --  data.code_type=ARGS.code_type
      if ARGS.code_type ==nil then
          ARGS.code_type="GRANT_CODE"
      end

--   ngx.log(ngx.ERR,ARGS.code_type)
      local bodyMap={}
      bodyMap.code_type    = ARGS.code_type
      bodyMap.code         = ARGS.code
      bodyMap.redirect_uri = ARGS.redirect_uri
      bodyMap.ip           = ip
      local requestData    = cjson.encode(bodyMap)
    --local data   = cjson.encode(apiReq)
    local query  = ngx.var.args

    do
      -- add X-Forwarded-For header
      headers['X-Forwarded-For'] = ngx.var.proxy_add_x_forwarded_for
    end

     --移除方法设定
  local rmvLowKey="x-http-method-override"
  --移除gzip设定
  local rmvKey2="accept-encoding"
  for k,v in pairs(headers) do
     local low=string.lower(k)
     if low==rmvLowKey  or low==rmvKey2   then
       headers[k]=nil
     end
  end

    -- perform http request
    local resp, err = httpclient.new()
      :uri(location)
      :headers(headers)
      :query(query)
      :body(requestData)
      :send(method, 2000, nil)

    if err or (not resp) then
      ngx.status = 500
      ngx.say(err)
      ngx.exit(ngx.OK)
      return res
    end

    -- response
    ngx.log(ngx.ERR,resp.body)
    res=cjson.decode(resp.body)
    if not res or not res.account then
      ngx.say(resp.body)
      ngx.exit(ngx.OK)
    end
    return res
  end
end



--根据用户id 到 datagateway取数据
local getAccInfo_Real=function(IdInfo)

  local headers=ngx.req.get_headers()
  --根ulr
  local ADDRESS = config.ENV.DATAGATE_SERVICE
  --后面接的path
  local ACTION  = string.format("%s/account",ngx.var.oauth_brand)
  local Req={account=IdInfo.account}


  if not ADDRESS or not ACTION then
    ngx.status = ngx.HTTP_NOT_FOUND
    ngx.exit(ngx.OK)
  end

  local location = ngx.unescape_uri(ADDRESS..ACTION)
  local method   = "PEEK"
  local headers  = ngx.req.get_headers()
  ngx.req.read_body()

  local data=cjson.encode(Req)
  local query  = ngx.var.args

  do

    headers['X-Forwarded-For'] = ngx.var.proxy_add_x_forwarded_for
  end
  --移除方法设定
  local rmvLowKey="x-http-method-override"
  --移除gzip设定
  local rmvKey2="accept-encoding"
  for k,v in pairs(headers) do
     local low=string.lower(k)
     if low==rmvLowKey  or low==rmvKey2   then
       headers[k]=nil
     end
  end

  for k,v in pairs(headers) do
    ngx.log(ngx.ERR,k..":"..v)

 end


  --重新装填 方法；移除或者指定为特定需要的method
  --ngx.log(ngx.ERR,method)
  headers['X-HTTP-Method-Override']=method
  -- perform http request
  local resp, err = httpclient.new()
    :uri(location)
    :headers(headers)
    :query(query)
    :body(data)
    :send(method, 2000, nil)

  if err or (not resp) then
    ngx.status = 500
    ngx.say(err)
    ngx.exit(ngx.OK)
  end

  -- response
  ngx.header['Server'] = ngx.var.SERVICE_NAME
  ngx.header['Content-Type'] = resp.headers['Content-Type']
  ngx.status = resp.status

  local rmvLowKey="content-length"
  --如果我们修改了回应的内容，不是和调用的service返回的长度一样，"content-length"需要拿掉，不然回复出去的长度对不上
  for k,v in pairs(resp.headers) do
     local low=string.lower(k)
     if low==rmvLowKey then
      resp.headers[k]=nil
     end
  end
  fill_response_header(resp.headers)


  local replyInfo=resp.body
  ngx.log(ngx.ERR,resp.body)
  local regRes=cjson.decode(replyInfo)
  local loginRes
  if  regRes and regRes.account then
      --成功了
      --按协议指定字段返回
       loginRes ={
        account                = regRes.account ,
        username               = regRes.username ,
        type                   = regRes.type ,
        level                  = regRes.level ,
        invitation_grade       = regRes.invitation_grade ,
        last_login_at          = regRes.last_login_at ,
        is_auth_login          = true ,
        last_password_change_at= regRes.last_password_change_at ,
        create_at              = regRes.create_at ,
        timestamp              = ngx.time() ,
      }
    replyInfo = cjson.encode(loginRes)
    call_nsq(loginRes)
  else
      --失败了，打印信息
      if resp.body then
        ngx.log(ngx.ERR,"dataService resonpce err"..resp.body)
      else
          ngx.log(ngx.ERR,"dataService resonpce err")
      end
  end


  --adjust
  do
    ngx.log(ngx.ERR, "adjust绑定-oauth-login1:", cjson.encode(regRes))
    ngx.log(ngx.ERR, "adjust绑定-oauth-login2:", cjson.encode(ARGS))
    if regRes and ARGS.adjust then --and regRes.create_at == regRes.update_at
      ngx.log(ngx.ERR, "adjust绑定-oauth-login3:")
      local dataapi    = require("shared.api.dataapi")
      local adjustArgs = ARGS.adjust
      local reply, err = dataapi.adjust_device.create(
        {
          account     = regRes.account or "",
          adid        = adjustArgs.adid or "",
          adid_type   = adjustArgs.adid_type or "",
          app_id      = adjustArgs.app_id or "",
          device_info = adjustArgs.device_info or nil,
        })
      if err then
        if err.message ~= "DUPLICATE_DEVICE" then
          ngx.log(ngx.ERR, "adjust绑定oauth-失败：", cjson.encode(err))
        end
      end
    end
  end


  ngx.say(replyInfo)
  ngx.exit(ngx.OK)
end


do
  local accIdInfo=getAccountIdInfo()
  getAccInfo_Real(accIdInfo)
end






